#ifndef SYSCALLS_C
#define SYSCALLS_C


void* interrupt_handlers[255];

void sysf_put()
{
	char byte = (char)popInt32();
	uint32_t handle = popInt32();
	write(handle,&byte,1);
}
void sysf_get()
{
	char dat = 0;
	uint32_t handle = popInt32();
	int stat = read(handle,&dat,1);
	if(stat == -1)
		pushDword(-1);
	else
		pushDword((int)dat);
}
void sysf_print()
{
	uint32_t  text  = popInt32();
	uint32_t handle = popInt32();
	int size = strlen((char*)&RAM[text]);
	
   	write(handle,&RAM[text],size);
}
void sysf_open()
{
	uint32_t  text  = popInt32();
	uint32_t  mode = popInt32();
	uint32_t  real_mode = 0;
	if(mode == 0)
		real_mode = O_WRONLY | O_CREAT;
	else if (mode == 1)	
		real_mode = O_RDONLY;
	else if (mode == 2)
		real_mode == O_WRONLY | O_APPEND;
	char* file =  (char*)&RAM[text];
	pushDword(open(file,real_mode,S_IRUSR | S_IWUSR) );
}
void sysf_close()
{
	close(popInt32());
}
void sysf_seek()
{
	uint32_t handle = popInt32();
	uint32_t pos = popInt32();
	pushDword(lseek(handle,pos,SEEK_SET));
}
void sysf_seekcur()
{
	uint32_t handle = popInt32();
	uint32_t pos = popInt32();
	pushDword(lseek(handle,pos,SEEK_CUR));
}
void sysf_seekend()
{
	uint32_t handle = popInt32();
	uint32_t pos = popInt32();
	pushDword(lseek(handle,pos,SEEK_END));
}
void sysf_read()
{
	uint32_t handle = popInt32();
	char* str = (char*)malloc(200);
	if(handle == 0)
		gets(str);
	else
	{
		read(handle,str,200);
		str[strlen(str) -1] = 0;
	}
	uint32_t tmp = heapalloc(strlen(str) + 2);
	memcpy(RAM + tmp,str,strlen(str) + 2);
	pushDword(tmp);

	free(str);
   	
}
void sysf_strcat()
{
	char* str2 = (char*)(RAM +  popInt32());
	char* str1 = (char*)(RAM +  popInt32());
	uint32_t size = (unsigned)strlen(str1) + (unsigned)strlen(str2);
	char* dat = (char*)malloc(size + 1);
	memcpy(dat,str1, strlen(str1));
	memcpy(dat + strlen(str1),str2, strlen(str2));
	//strcpy((char*)(&RAM + heapPointer),dat);
	dat[size] = 0;
	uint32_t tmp = heapalloc(size + 1);
	memcpy(RAM + tmp, dat,size + 1);
	pushDword(tmp);
   	free(dat);
}
void sysf_strcmp()
{
	char* str2 = (char*)(RAM +  popInt32());
	char* str1 = (char*)(RAM +  popInt32());
	if(strcmp(&str1[0],&str2[0]) == 0)
	{
		pushDword(1);
	}
	else
		pushDword(0);
   	
}
void sysf_tostr()
{
	char* str = (char*)(RAM +  popInt32());
	uint32_t val = atoi(str);
	pushDword(val);
   	
}
void sysf_toint()
{
	int32_t aInt = popInt32();
	char str[15];
	sprintf(str, "%d", aInt);
	uint32_t tmp = heapalloc(strlen(str) + 1);
	str[strlen(str)] = 0;
	memcpy(RAM + tmp, str,strlen(str) + 1);
	pushDword(tmp);
}

void sysf_fota()
{
	char str[15];
	sprintf(str, "%f", popFloat());
	uint32_t tmp = heapalloc(strlen(str) + 1);
	str[strlen(str)] = 0;
	memcpy(RAM + tmp, str,strlen(str) + 1);
	pushDword(tmp);
}

#endif
